package com.example.weight.greenSeasons.SolidLiquid;
import com.example.weight.R;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.weight.greenSeasons.flocculation.xuningribaoyang;
import com.example.weight.greenSeasons.waterDeal.EquipmentDailyMaintainTable;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.researchDevelopment.OutcomingScene;
import com.example.weight.householdWaste.AbnormalRubbishActivity;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class ribaoyang7_5 extends AppCompatActivity {

    //下拉框
    private ExpandableLayout expandable_1;
    private Button ButtonNo1;
    private ExpandableLayout expandable_2;
    private Button ButtonNo2;
    private ExpandableLayout expandable_3;
    private Button ButtonNo3;
    private ExpandableLayout expandable_4;
    private Button ButtonNo4;
    /*
    private ExpandableLayout expandable_5;
    private Button ButtonNo5;*/

    private TitleBar titleBar;

    //日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;

    //操作人，名字角色
    private String name, role, factory;

    //设备复选框
    private CheckBox duijiekou1,duijiekou2,fenli1,fenli2,fenli1controll,fenli2controll,wuzhou;//chuchou1,chuchou2;
    //设备检查框
    private CheckBox duijiekou1_check,duijiekou2_check,fenli1_check,fenli2_check,fenli1controll_check,fenli2controll_check,wuzhou_check;//chuchou1_check,chuchou2_check;
    //设备备注
    private EditText duijiekou1_remark,duijiekou2_remark,fenli1_remark,fenli2_remark,fenli1controll_remark,fenli2controll_remark,wuzhou_remark;//chuchou1_remark,chuchou2_remark;

    private Map<String, String> fromIdMap;

    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ribaoyang7_5);

        //角色
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        //日期
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));
        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                ribaoyang7_5.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        //下拉框
        expandable_1=findViewById(R.id.expandable_1);
        ButtonNo1=findViewById(R.id.button1);
        expandable_2=findViewById(R.id.expandable_2);
        ButtonNo2=findViewById(R.id.button2);
        expandable_3=findViewById(R.id.expandable_3);
        ButtonNo3=findViewById(R.id.button3);
        expandable_4=findViewById(R.id.expandable_4);
        ButtonNo4=findViewById(R.id.button4);
        /*
        expandable_5=findViewById(R.id.expandable_5);
        ButtonNo5=findViewById(R.id.button5);*/
        //获取设备控件
        duijiekou1 = findViewById(R.id.duijiekou1);
        duijiekou2 = findViewById(R.id.duijiekou2);
        fenli1 = findViewById(R.id.fenli1);
        fenli2 = findViewById(R.id.fenli2);
        fenli1controll = findViewById(R.id.fenli1controll);
        fenli2controll = findViewById(R.id.fenli2controll);
        wuzhou = findViewById(R.id.wuzhou);
        /*
        chuchou1 = findViewById(R.id.chuchou1);
        chuchou2 = findViewById(R.id.chuchou2);*/

        duijiekou1_check = findViewById(R.id.duijiekou1_check);
        duijiekou2_check = findViewById(R.id.duijiekou2_check);
        fenli1_check = findViewById(R.id.fenli1_check);
        fenli2_check = findViewById(R.id.fenli2_check);
        fenli1controll_check = findViewById(R.id.fenli1controll_check);
        fenli2controll_check = findViewById(R.id.fenli2controll_check);
        wuzhou_check = findViewById(R.id.wuzhou_check);
        /*
        chuchou1_check = findViewById(R.id.chuchou1_check);
        chuchou2_check = findViewById(R.id.chuchou2_check);*/

        duijiekou1_remark = findViewById(R.id.duijiekou1_remark);
        duijiekou2_remark = findViewById(R.id.duijiekou2_remark);
        fenli1_remark = findViewById(R.id.fenli1_remark);
        fenli2_remark = findViewById(R.id.fenli2_remark);
        fenli1controll_remark = findViewById(R.id.fenli1controll_remark);
        fenli2controll_remark = findViewById(R.id.fenli2controll_remark);
        wuzhou_remark = findViewById(R.id.wuzhou_remark);
        /*
        chuchou1_remark = findViewById(R.id.chuchou1_remark);
        chuchou2_remark = findViewById(R.id.chuchou2_remark);*/

        fromIdMap = new HashMap<>();

        queue = Volley.newRequestQueue(this);

        try {
            setCheckStatus(duijiekou1, duijiekou1_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(duijiekou2, duijiekou2_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(fenli1, fenli1_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(fenli2, fenli2_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(fenli1controll, fenli1controll_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(fenli2controll, fenli2controll_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(wuzhou, wuzhou_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        /*
        try {
            setCheckStatus(chuchou1, chuchou1_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            setCheckStatus(chuchou2, chuchou2_check);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/

        if (role.equals("操作人")) {
            duijiekou1_check.setEnabled(false);
            duijiekou2_check.setEnabled(false);
            fenli1_check.setEnabled(false);
            fenli2_check.setEnabled(false);
            fenli1controll_check.setEnabled(false);
            fenli2controll_check.setEnabled(false);
            wuzhou_check.setEnabled(false);
            /*
            chuchou1_check.setEnabled(false);
            chuchou2_check.setEnabled(false);*/
        }/*else{
            duijiekou1.setEnabled(false);
            duijiekou2.setEnabled(false);
            fenli1.setEnabled(false);
            fenli2.setEnabled(false);
            fenli1controll.setEnabled(false);
            fenli2controll.setEnabled(false);
            wuzhou.setEnabled(false);
            chuchou1.setEnabled(false);
            chuchou2.setEnabled(false);

            duijiekou1_remark.setEnabled(false);
            duijiekou2_remark.setEnabled(false);
            fenli1_remark.setEnabled(false);
            fenli2_remark.setEnabled(false);
            fenli1controll_remark.setEnabled(false);
            fenli2controll_remark.setEnabled(false);
            wuzhou_remark.setEnabled(false);
            chuchou1_remark.setEnabled(false);
            chuchou2_remark.setEnabled(false);
        }*/
        // 操作人填表
        duijiekou1.setOnClickListener(v -> {
            if (duijiekou1.isChecked()) {
                operatorAddForm(duijiekou1, duijiekou1_remark.getText().toString());
            }
        });
        duijiekou2.setOnClickListener(v -> {
            if (duijiekou2.isChecked()) {
                operatorAddForm(duijiekou2, duijiekou2_remark.getText().toString());
            }
        });
        fenli1.setOnClickListener(v -> {
            if (fenli1.isChecked()) {
                operatorAddForm(fenli1, fenli1_remark.getText().toString());
            }
        });
        fenli2.setOnClickListener(v -> {
            if (fenli2.isChecked()) {
                operatorAddForm(fenli2, fenli2_remark.getText().toString());
            }
        });
        fenli1controll.setOnClickListener(v -> {
            if (fenli1controll.isChecked()) {
                operatorAddForm(fenli1controll, fenli1controll_remark.getText().toString());
            }
        });
        fenli2controll.setOnClickListener(v -> {
            if (fenli2controll.isChecked()) {
                operatorAddForm(fenli2controll, fenli2controll_remark.getText().toString());
            }
        });
        wuzhou.setOnClickListener(v -> {
            if (wuzhou.isChecked()) {
                operatorAddForm(wuzhou, wuzhou_remark.getText().toString());
            }
        });
        /*
        chuchou1.setOnClickListener(v -> {
            if (chuchou1.isChecked()) {
                operatorAddForm(chuchou1, chuchou1_remark.getText().toString());
            }
        });
        chuchou2.setOnClickListener(v -> {
            if (chuchou2.isChecked()) {
                operatorAddForm(chuchou2, chuchou2_remark.getText().toString());
            }
        });*/
        // 检查人填表
        duijiekou1_check.setOnClickListener(v -> {
            if (duijiekou1_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(duijiekou1.getText().toString())) != null)
                    examinerAddForm(fromId, duijiekou1_remark.getText().toString(), duijiekou1_check);
            }
        });
        duijiekou2_check.setOnClickListener(v -> {
            if (duijiekou2_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(duijiekou2.getText().toString())) != null)
                    examinerAddForm(fromId, duijiekou2_remark.getText().toString(), duijiekou2_check);
            }
        });
        fenli1_check.setOnClickListener(v -> {
            if (fenli1_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fenli1.getText().toString())) != null)
                    examinerAddForm(fromId, fenli1_remark.getText().toString(), fenli1_check);
            }
        });
        fenli2_check.setOnClickListener(v -> {
            if (fenli2_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fenli2.getText().toString())) != null)
                    examinerAddForm(fromId, fenli2_remark.getText().toString(), fenli2_check);
            }
        });
        fenli1controll_check.setOnClickListener(v -> {
            if (fenli1controll_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fenli1controll.getText().toString())) != null)
                    examinerAddForm(fromId, fenli1controll_remark.getText().toString(), fenli1controll_check);
            }
        });
        fenli2controll_check.setOnClickListener(v -> {
            if (fenli2controll_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fenli2controll.getText().toString())) != null)
                    examinerAddForm(fromId, fenli2controll_remark.getText().toString(), fenli2controll_check);
            }
        });
        wuzhou_check.setOnClickListener(v -> {
            if (wuzhou_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(wuzhou.getText().toString())) != null)
                    examinerAddForm(fromId, wuzhou_remark.getText().toString(), wuzhou_check);
            }
        });
        /*
        chuchou1_check.setOnClickListener(v -> {
            if (chuchou1_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(chuchou1.getText().toString())) != null)
                    examinerAddForm(fromId, chuchou1_remark.getText().toString(), chuchou1_check);
            }
        });
        chuchou2_check.setOnClickListener(v -> {
            if (chuchou2_check.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(chuchou2.getText().toString())) != null)
                    examinerAddForm(fromId, chuchou2_remark.getText().toString(), chuchou2_check);
            }
        });*/
    }
    public void show1(View view) {
        if (expandable_1.isExpanded()){
            ButtonNo1.setText("+ 擦拭冲刷");
        }else{
            ButtonNo1.setText("- 擦拭冲刷");
        }
        expandable_1.toggle();
    }
    public void show2(View view) {
        if (expandable_2.isExpanded()){
            ButtonNo2.setText("+ 擦拭箱体，清理耙齿、栅缝，冲洗内部");
        }else{
            ButtonNo2.setText("- 擦拭箱体，清理耙齿、栅缝，冲洗内部");
        }
        expandable_2.toggle();
    }
    public void show3(View view) {
        if (expandable_3.isExpanded()){
            ButtonNo3.setText("+ 擦拭箱体表面");
        }else{
            ButtonNo3.setText("- 擦拭箱体表面");
        }
        expandable_3.toggle();
    }
    public void show4(View view) {
        if (expandable_4.isExpanded()){
            ButtonNo4.setText("+ 擦拭卫生");
        }else{
            ButtonNo4.setText("- 擦拭卫生");
        }
        expandable_4.toggle();
    }
    /*
    public void show5(View view) {
        if (expandable_5.isExpanded()){
            ButtonNo5.setText("+ 擦拭检查噪声");
        }else{
            ButtonNo5.setText("- 擦拭检查噪声");
        }
        expandable_5.toggle();
    }*/

    //功能相关
    private void examinerAddForm(String formId, String comment, CheckBox checkBox) {
        new AlertDialog.Builder(this)
                .setTitle("确定检查吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    String url = Config.url + "/sjq/solidliquidProduceMaintenanceDay/add_examiner";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(ribaoyang7_5.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(ribaoyang7_5.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ribaoyang7_5.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("Id", formId);
                            map.put("examiner", name);
                            map.put("remarks", comment);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }
    private void operatorAddForm(CheckBox checkBox, String comment) {
        String fName = checkBox.getText().toString();
        String maintainstr="";
        switch (fName) {
            case "对接口1":
            case "对接口2":
                maintainstr="擦拭冲刷";
                break;
            case "固液分离机1":
            case "固液分离机2":
                maintainstr="擦拭箱体，清理耙齿、栅缝，冲洗内部";
                break;
            case "固液分离机1控制系统":
            case "固液分离机2控制系统":
                maintainstr="擦拭箱体表面";
                break;
            case "无轴螺旋输送机":
                maintainstr="擦拭卫生";
                break;
            case "1#除臭系统":
            case "2#除臭系统":
                maintainstr="擦拭检查噪声";
                break;
            default:
                maintainstr="";
                break;
        }
        String maintainContent=maintainstr;
        new android.app.AlertDialog.Builder(this)
                .setTitle("确定提交吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    String url = Config.url + "/sjq/solidliquidProduceMaintenanceDay/add_recorder";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(ribaoyang7_5.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(ribaoyang7_5.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ribaoyang7_5.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenance_content", maintainContent);
                            //map.put("isNormal", comment.equals("")?"1":"0");
                            map.put("remarks", comment);
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }
    private void setCheckStatus(CheckBox operatorCB, CheckBox examinerCB) throws UnsupportedEncodingException{
        String fName = operatorCB.getText().toString();
        String maintainstr="";
        switch (fName) {
            case "对接口1":
            case "对接口2":
                maintainstr="擦拭冲刷";
                break;
            case "固液分离机1":
            case "固液分离机2":
                maintainstr="擦拭箱体，清理耙齿、栅缝，冲洗内部";
                break;
            case "固液分离机1控制系统":
            case "固液分离机2控制系统":
                maintainstr="擦拭箱体表面";
                break;
            case "无轴螺旋输送机":
                maintainstr="擦拭卫生";
                break;
            case "1#除臭系统":
            case "2#除臭系统":
                maintainstr="擦拭检查噪声";
                break;
            default:
                maintainstr="";
                break;
        }
        String maintainContent=maintainstr;
        String operatorCBText = fName+" "+maintainContent;
        String fName1 = URLEncoder.encode(fName, "utf-8");
        maintainContent = URLEncoder.encode(maintainContent, "utf-8");
        String url = Config.url + "/sjq/solidliquidProduceMaintenanceDay/getlatest"+"?equipment_name="+fName1+"&maintenance_content="+maintainContent + "&factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("res",response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                operatorCB.setChecked(true);
                                operatorCB.setEnabled(false);
                                operatorCB.setTextColor(Color.GREEN);
                                setRemarks(operatorCB, data.getString("remarks"));

                                String examiner = data.getString("examiner");
                                if (!examiner.equals("") && !examiner.equals("null")) {
                                    // 检查人已检查某项，该项不可再检查
                                    examinerCB.setChecked(true);
                                    examinerCB.setEnabled(false);
                                    examinerCB.setTextColor(Color.GREEN);
                                } else {
                                    // 若存在检查人未检查项，将其添加到formIdList中
                                    fromIdMap.put(fName, data.getString("id"));
                                }
                            } else {
                                if (role.equals("检查人")) {
                                    // 如果操作人未保养，检查人不可检查
                                    operatorCB.setEnabled(false);
                                    examinerCB.setEnabled(false);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ribaoyang7_5.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    private void setRemarks(CheckBox checkBox, String remarks) {
        switch (checkBox.getText().toString()) {
            case "对接口1":
                duijiekou1_remark.setText(remarks);
                break;
            case "对接口2":
                duijiekou2_remark.setText(remarks);
                break;
            case "固液分离机1":
                fenli1_remark.setText(remarks);
                break;
            case "固液分离机2":
                fenli2_remark.setText(remarks);
                break;
            case "固液分离机1控制系统":
                fenli1controll_remark.setText(remarks);
                break;
            case "固液分离机2控制系统":
                fenli2controll_remark.setText(remarks);
                break;
            case "无轴螺旋输送机":
                wuzhou_remark.setText(remarks);
                break;
                /*
            case "1#除臭系统":
                chuchou1_remark.setText(remarks);
                break;
            case "2#除臭系统":
                chuchou2_remark.setText(remarks);
                break;*/
            default:
                break;
        }
    }
}